package com.nineclock.system.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.sms.AliyunSmsUtils;
import com.nineclock.common.utils.PhoneNumCheckUtils;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.service.SmsService;
import com.nineclock.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.Duration;

@Service
@Transactional
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Autowired
    private SysUserService userService;

    @Autowired
    private AliyunSmsUtils smsUtils;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public void sendSmsCode(String mobile, String type) {
        // 1.参数校验
        // 1.1 参数为空校验
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(type)) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        // 1.2 校验手机号码格式
        if (!PhoneNumCheckUtils.isPhoneLegal(mobile)) {
            // 如果手机号码格式不对，抛出异常
            throw new NcException(ResponseEnum.INVALID_PHONE_NUMBER);
        }

        // 1.3 如果是登录、重置密码、更换管理员，手机号码必须存在，否则手机号码必须不存在
        SysUserDTO userDTO = userService.queryUser(mobile);

        if (type.equals(SMSConstant.SMS_TYPE_REGISTER)) { // 如果是注册
            if (userDTO != null) {
                throw new NcException(ResponseEnum.USER_MOBILE_EMAIL_EXISTS);
            }

        } else {
            if(userDTO == null){
                throw new NcException(ResponseEnum.USER_NOT_REGISTER);
            }
        }

        // 2.调用阿里云短信，发送验证码
        String code = RandomUtil.randomNumbers(6); // 生成6位数随机验证码
        // Boolean sendResult = smsUtils.sendSMS(mobile, code);
        // if(!sendResult){
            //throw new NcException(ResponseEnum.SEND_MESSAGE_ERROR);
        // }

        // 3.存储验证码到Redis
        String prefix = getPrefix(type);
        String key = prefix + mobile; // 拼接key
        redisTemplate.opsForValue().set(key, code, Duration.ofMinutes(5));

        log.info("短信发送成功，手机号 = " + mobile + "，业务类型 = " + type + "，验证码 = " + code);

    }



    /**
     * 根据操作类型，获取验证码前缀
     * @param type
     * @return
     */
    private String getPrefix(String type){
        String prefix = "";
        switch (type){
            case "1":
                prefix = SMSConstant.SMS_LOGIN_KEY_PREFIX;//登录
                break;
            case "2":
                prefix = SMSConstant.SMS_REGISTER_KEY_PREFIX;//注册
                break;
            case "3":
                prefix = SMSConstant.SMS_CHANGE_MANAGER_KEY_PREFIX;//更改管理员
                break;
            case "4":
                prefix = SMSConstant.SMS_RESET_KEY_PREFIX;//重置密码
                break;
            default:
                break;
        }
        return prefix;
    }

    @Override
    public Boolean verifyCode(String mobile, String checkcode, String type) {
        // 参数校验
        if(StringUtils.isEmpty(mobile) || StringUtils.isEmpty(checkcode) || StringUtils.isEmpty(type)){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        // 从redis取出验证码，和传入的验证码进行对比
        String prefix = getPrefix(type);
        String key = prefix + mobile; // 拼接key
        String redisCode = (String) redisTemplate.opsForValue().get(key);

        if(!StringUtils.isEmpty(redisCode) && redisCode.equals(checkcode)){
            // 校验完删除验证码
            redisTemplate.delete(key);
            return true;
        }
        return false;
    }

}
